package com.atguigu.uitl;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author hjy
 * @create 2023/3/20 14:25
 */
public class DimUtil {
    public static JSONObject getDim(Connection connection,String tableName,String id) throws Exception {
        //todo 优化--->旁路缓存  将数据存在redis中  主键选用DIM：tableName+id
        Jedis jedis = JedisUtil.getJedis();
        String redisKey = "DIM:" + tableName + ":" + id;
        String dimInfoStr = jedis.get(redisKey);
        if (dimInfoStr!=null){
            //todo 刷新key的存活时间
            jedis.expire(redisKey,24*36000);
            jedis.close();
            return JSONObject.parseObject(dimInfoStr);
        }

        //从phoenix读取数据
        //sql 拼接
        String sql="select * from "+ GmallConfig.HBASE_SCHEMA+"."+tableName+" where   id='"+id+"'";
        List<JSONObject> values = JdbcUtil.getJDBC(connection, sql, JSONObject.class, false);
        JSONObject dimInfo = values.get(0);
        //将数据放入redis
        jedis.setex(redisKey,24*3600,dimInfo.toJSONString());
        jedis.close();
        return dimInfo;
    }

    public static void main(String[] args) throws Exception {
        DruidPooledConnection phoenixConn = DruidDSUtil.getPhoenixConn();
        long start = System.currentTimeMillis();
        JSONObject jsonObject = getDim(phoenixConn, "DIM_BASE_CATEGORY1", "18");//110 112 106
        long end = System.currentTimeMillis();
        JSONObject jsonObject2 = getDim(phoenixConn, "DIM_BASE_CATEGORY1", "19");//10 8   8
        //2  2  1  1
        long end2 = System.currentTimeMillis();

        System.out.println(jsonObject);

        System.out.println(end - start);
        System.out.println(end2 - end);
    }
}
